// pages/phone-verification/phone-verification.ts
import {PAGE_HOME, goToPage, PAGES} from '../../../config/pages';
import {registerVerify, verifyCode} from "../../../api/api";
import {phoneLogin} from "../../../api/public";
import util from "../../../utils/util";
import {getUserInfo, phoneSilenceAuth} from "../../../api/user";
import Routine from "../../../libs/routine";
import store from "../../../store/index.js";
import cache from "../../../utils/cache";

Page({
  data: {
    selectedCountry: '中国大陆',
    countryCode: '+86',
    phoneNumber: '',
    verificationCode: '',
    realName: '',
    corpName: '',
    savePhone: false,
    countdownSeconds: 0,
    isFormValid: false,
    authKey: ''
  },

  onLoad(options: any) {
    console.log('手机验证页面加载完成');
    // 检查是否有搜索关键词参数
    if (options && options.authKey) {
      this.setData({
        authKey: options.authKey
      });
    }
  },

  onShow() {
    console.log('手机验证页面显示');
  },

  // 选择国家/地区
  selectCountry() {
    const countries = [
      { name: '中国大陆', code: '+86' },
      // { name: '中国香港', code: '+852' },
      // { name: '中国台湾', code: '+886' },
      // { name: '美国', code: '+1' },
      // { name: '日本', code: '+81' },
      // { name: '韩国', code: '+82' }
    ];
    
    const countryNames = countries.map(country => country.name);
    
    wx.showActionSheet({
      itemList: countryNames,
      success: (res) => {
        const selectedIndex = res.tapIndex;
        if (selectedIndex >= 0 && selectedIndex < countries.length) {
          this.setData({
            selectedCountry: countries[selectedIndex].name,
            countryCode: countries[selectedIndex].code
          });
        }
      }
    });
  },

  // 手机号输入变化
  onPhoneChange(e: any) {
    this.setData({
      phoneNumber: e.detail.value
    });
    this.validateForm();
  },

  // 验证码输入变化
  onCodeChange(e: any) {
    this.setData({
      verificationCode: e.detail.value
    });
    this.validateForm();
  },

  // 姓名输入变化
  onRealNameChange(e: any) {
    this.setData({
      realName: e.detail.value
    });
    this.validateForm();
  },

  // 企业名称输入变化
  onCorpNameChange(e: any) {
    this.setData({
      corpName: e.detail.value
    });
    this.validateForm();
  },

  // 验证表单
  validateForm() {
    const { phoneNumber, verificationCode, realName } = this.data;
    const isValidPhone = /^1[3-9]\d{9}$/.test(phoneNumber);
    const isValidCode = /^\d{6}$/.test(verificationCode);
    const isValidName = realName.trim().length > 0;
    
    this.setData({
      isFormValid: isValidPhone && isValidCode && isValidName
    });
  },

  // 发送验证码
  sendVerificationCode() {
    const { phoneNumber } = this.data;
    
    if (!phoneNumber) {
      wx.showToast({
        title: '请先输入手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号格式',
        icon: 'none'
      });
      return;
    }

    verifyCode().then(res => {
      registerVerify(phoneNumber, 'reset', res.data.key, '', '')
          .then(res => {
            util.Tips({
              title: res.msg
            });
            // 模拟发送验证码
            this.startCountdown();
          }).catch(err => {
        return util.Tips({
          title: err
        });
      });
    });

    
    // 模拟验证码发送成功
    // wx.showModal({
    //   title: '验证码已发送',
    //   content: `验证码已发送到 ${this.data.countryCode} ${phoneNumber}`,
    //   showCancel: false
    // });
  },

  // 开始倒计时
  startCountdown() {
    this.setData({
      countdownSeconds: 60
    });
    
    const timer = setInterval(() => {
      const newCountdown = this.data.countdownSeconds - 1;
      this.setData({
        countdownSeconds: newCountdown
      });
      
      if (newCountdown <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  },

  // 切换保存手机号选项
  toggleSaveOption() {
    this.setData({
      savePhone: !this.data.savePhone
    });
  },

  /**
   * 获取个人用户信息
   */
  getUserInfo: function(new_user) {
    let that = this;
    getUserInfo().then(res => {
      wx.hideLoading();
      // that.userInfo = res.data
      store.commit("app/SETUID", res.data.uid);
      store.commit("app/UPDATE_USERINFO", res.data);
      util.Tips({
        title: (`登录成功`),
        icon: 'success'
      }, {
        tab: 4,
        url: PAGES.HOME
      })
    });
  },

  // 确认验证
  confirmVerification() {
    const { phoneNumber, verificationCode, realName, corpName, savePhone, selectedCountry, countryCode } = this.data;
    
    if (!phoneNumber) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号格式',
        icon: 'none'
      });
      return;
    }
    
    if (!verificationCode) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }

    if (!realName.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }

    const app = getApp();

    if (this.data.authKey){
      phoneLogin({
        key: this.data.authKey,
        spread_spid: app.globalData.spid,
        spread_code: '',
        phone: phoneNumber,
        captcha: verificationCode,
        real_name: realName,
        corp_name: corpName
      }).then(res => {
        console.log(res);
        let time = res.data.expires_time - cache.time();
        store.commit('app/LOGIN', {
          token: res.data.token,
          time: time
        });
        this.getUserInfo(res.data.new_user);
      }).catch(error => {
        util.Tips({
          title: error
        })
      })

    }else{
      Routine.getCode()
          .then(code => {

            phoneLogin({
              code: code,
              spread_spid: app.globalData.spid,
              spread_code: '',
              phone: phoneNumber,
              captcha: verificationCode,
              real_name: realName,
              corp_name: corpName
            }).then(res => {
              console.log(res);
              let time = res.data.expires_time - cache.time();
              store.commit('app/LOGIN', {
                token: res.data.token,
                time: time
              });
              this.getUserInfo(res.data.new_user);
            }).catch(error => {
              util.Tips({
                title: error
              })
            })
          })
          .catch(error => {
            console.log(error);
            wx.hideLoading();
          });
    }

  }
});
